package com.five.taotao.Adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.bumptech.glide.Glide;
import com.five.taotao.R;
import com.five.taotao.entity.Product;

import java.util.List;

/**
 * Created by asus on 2016/9/17.
 */
public class GridAdapter extends BaseAdapter {

    private List<Product.ListBean> mData;
    private Context mContext;
    private DisplayMetrics dm;

    public GridAdapter(List<Product.ListBean> mData, Context mContext) {
        this.mData = mData;
        this.mContext = mContext;
    }

    public GridAdapter(List<Product.ListBean> mData, Context mContext, DisplayMetrics dm) {
        this.mData = mData;
        this.mContext = mContext;
        this.dm = dm;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final Product.ListBean product = mData.get(position);
        //布局加载器
        LayoutInflater inflater = LayoutInflater.from(mContext);//参数要有 上下文 Context
        ViewHolder holder;
        /**
         * ConvertView 回收视图，效率提高 200%
         *
         * 如果原先没有convertView，就加载布局
         */
        if (convertView == null) {
            //加载布局
            convertView = inflater.inflate(R.layout.grid_item, null, false);
            //缓存对象
            holder = new ViewHolder();//
            holder.img = (ImageView) convertView.findViewById(R.id.img);

            holder.product_name = (TextView) convertView.findViewById(R.id.product_name);

            convertView.setTag(holder);//View 关联 Holder
        } else {

            holder = (ViewHolder) convertView.getTag();//若果有 加载 ViewHolder
        }

        Glide.with(mContext)
                .load(product.getUrl())
                .placeholder(R.drawable.store_default1)//占位图片
                .error(R.drawable.store_default1)//加载错误图片
                .thumbnail(0.8f)//预加载透明度
                .into(holder.img);
        holder.product_name.setText(product.getName());

        return convertView;//返回View对象
    }

    static class ViewHolder {
        ImageView img;
        TextView product_name;
    }
}
